package com.crossriver.crgis.portlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crossriver.crgis.cofo.util.ApplicationActionUtil;
import com.crossriver.crgis.cofo.util.ApplicationCofOConstants;
import com.crossriver.crgis.cofo.util.CofORetrieveUtil;
import com.crossriver.crgis.cofo.util.Emailer;
import com.crossriver.crgis.database.model.Application_C_of_O;
import com.crossriver.crgis.database.model.Company_Contact_Person;
import com.crossriver.crgis.database.model.Contact_Information;
import com.crossriver.crgis.database.model.Documents;
import com.crossriver.crgis.database.model.Individual_Information;
import com.crossriver.crgis.database.model.Supporting_Document;
import com.crossriver.crgis.database.service.Application_C_of_OLocalServiceUtil;
import com.crossriver.crgis.database.service.Company_Contact_PersonLocalServiceUtil;
import com.crossriver.crgis.database.service.Contact_InformationLocalServiceUtil;
import com.crossriver.crgis.database.service.Individual_InformationLocalServiceUtil;
import com.crossriver.crgis.mail.util.MailMessages;
import com.crossriver.crgis.cofo.util.DownloadUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.servlet.SessionMessages;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.util.PortalUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class BOCofO
 */
public class BOCofO extends MVCPortlet {
	
	private static Log log = LogFactory.getLog(BOCofO.class);
	
	public void changeApplicationStatus(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		
		String applicationId = ParamUtil.getString(actionRequest, "applicationId");
		String applStatus = ParamUtil.getString(actionRequest, "applStatus");
		
		//get the application status, do the change and send the mail
		
		try {
			Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
			application.setStatus(applStatus);
			
			Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application);
			
			
			if("APPLICATION READY".equalsIgnoreCase(applStatus)){
				//prepare mail and send it.
				String message = MailMessages.APPLICATION_READY;
				
				String appType = application.getApplicationType();
				Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);

				String emailAddr = contact.getEmailAddress();
				
				if("Individual".equalsIgnoreCase(appType)){
					
					Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
					
					message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
				}else{
					
					Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
					
					
					message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
				}
				message = message.replaceAll("#SERVICE_NAME#", application.getApplication().toUpperCase());
				
				
				//send mail to the CRGIS for notification of of completed application
				String from ="crgis@crossriverstate.gov.ng";
				String to = emailAddr;
				String bcc=null;
				String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
				
				File[] attachments = null;
				
				try {
					Emailer.sendEmail(from, to, bcc, subject, message, attachments );
				} catch (Exception e) {
					SessionErrors.add(actionRequest, "problem-sending-mail");
					if(log.isInfoEnabled()){
						log.info(e.getMessage());
					}
					e.printStackTrace();
				}
				
				
			}else if("CANCELLED".equalsIgnoreCase(applStatus)){
				String message = MailMessages.CANCELLED;
				
				String appType = application.getApplicationType(); 
				Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
				String emailAddr = contact.getEmailAddress();
				
				
				if("Individual".equalsIgnoreCase(appType)){
					
					Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
					
					message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());	
					
				}else{
					
					Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
					
					
					message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
					message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
					
				}
				message = message.replaceAll("#SERVICE_NAME#", application.getApplication().toUpperCase());
				
				
				//send mail to the CRGIS for notification of of completed application
				String from ="crgis@crossriverstate.gov.ng";
				String to = emailAddr;
				String bcc=null;
				String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
				
				File[] attachments = null;
				
				try {
					Emailer.sendEmail(from, to, bcc, subject, message, attachments );
				} catch (Exception e) {
					SessionErrors.add(actionRequest, "problem-sending-mail");
					if(log.isInfoEnabled()){
						log.info(e.getMessage());
					}
					e.printStackTrace();
				}
				
				
			}
			
			
			//CANCELLED
			//MailMessages.C_OF_O_READY
			
			
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
 

	public void pushAppToILS(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		
		//check the status
		String applicationId = ParamUtil.getString(actionRequest, "applicationId");
		Application_C_of_O applicationCofO = null;
		try {
			applicationCofO = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(applicationId);
		} catch (PortalException e) {
			 if(log.isInfoEnabled()){
				 log.info("There is a problem retrieving application information for " + applicationId);
			 }
			//e.printStackTrace();
		} catch (SystemException e) {
			if(log.isInfoEnabled()){
				 log.info("There is a problem retrieving application information for " + applicationId);
			 }
		}
		
		String status = applicationCofO.getStatus();
		
		viewApplicationDetail( actionRequest,  actionResponse);

		
		if("new".equalsIgnoreCase(status) ){
			SessionErrors.add(actionRequest, "functionality-under-development");
		}else{
			SessionErrors.add(actionRequest, "functionality-under-development");
		}
	}
	public void viewApplicationDetail(ActionRequest actionRequest, 
			ActionResponse actionResponse){

		if (log.isInfoEnabled()){
		log.info("In  viewApplicationDetail" );
		}
		Application_C_of_O appCofO = ApplicationActionUtil.
						getApplication_C_of_OFromRequest(actionRequest);
	
		if (log.isInfoEnabled()){
			log.info("successfully retrieved  AttestationInformation from the web >>> " 
				+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
		
	
		Application_C_of_O appCofOTemp = appCofO;
		try {
			if (log.isInfoEnabled()){
			log.info("successfully retrieved AttestationInformation for update >>> " 
					+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
			appCofOTemp = Application_C_of_OLocalServiceUtil.
					getApplication_C_of_O(appCofO.getApplicationId());
			
			appCofOTemp.setAttestation(appCofO.getAttestation());
			
			Application_C_of_OLocalServiceUtil.
				updateApplication_C_of_O(appCofOTemp);
			if (log.isInfoEnabled()){
			log.info("successfully saved  AttestationInformation  >>> " 
					+ appCofO.toString() +"<<< " + appCofO.getApplicationId()  );}
			
	
			
		} catch (PortalException e) {
			if (log.isDebugEnabled()){
			log.debug("Updating Application >>" + appCofOTemp.toString() + " <<< failed");
			log.debug("There is a problem persisting Application information " +e.getMessage());
			}
			//do a page for application error.
			actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");
	
			
			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		} catch (SystemException e) {
			if (log.isDebugEnabled()){
			log.debug("Updating Application >>" + appCofOTemp.toString() + " <<< failed");
			log.debug("There is a problem persisting Application information " +e.getMessage());
			}
			//do a page for application error.
			actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	        actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");
	
			
			SessionErrors.add(actionRequest, "application-error");
			e.printStackTrace();
			return;
		}
		
		
		//TODO
		//retrieve all the information that has been saved and put them on the 
		//request scope.
		//assume that their is failure
		actionRequest.setAttribute("jspPage", "/html/application_cofo/ApplicationError.jsp");
	    actionResponse.setRenderParameter("jspPage", "/html/application_cofo/ApplicationError.jsp");
		SessionErrors.add(actionRequest, "application-error");
	
		String applicationType = appCofOTemp.getApplicationType();
		
		//check application
		boolean retreiveInformation = 
			CofORetrieveUtil.extractApplicationInfoForDisplay(actionRequest,  appCofOTemp);
		
		
		
		//test personal info
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_INDIVIDUAL)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractPersonalInfoForDisplay(actionRequest,  appCofOTemp);
			}	
		}
		
		//do company information
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_ORGANISATION)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractOrganisationInfoForDisplay(actionRequest,  appCofOTemp);
			}	
		}
		
		//do company contact
		if(applicationType.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_ORGANISATION)){
			if( retreiveInformation){
				retreiveInformation = CofORetrieveUtil.extractCompanyContactInfoForDisplay(actionRequest,  appCofOTemp);
			}	
		}
		
		
		//test contact info
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractContactInfoForDisplay(actionRequest,  appCofOTemp);
		}
		
		//application history
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractApplicationHistForDisplay(actionRequest,  appCofOTemp);
		}
		
		//test property info
		if( retreiveInformation){
			retreiveInformation = CofORetrieveUtil.extractPropertyInfoForDisplay(actionRequest,  appCofOTemp);
		}
		
		//test supporting docs
		if( retreiveInformation){
			retreiveInformation = 
				CofORetrieveUtil.extractSupportDocForDisplay(actionRequest,  appCofOTemp);
		}
		
		log.info("Successfully all the information for display >>> " +appCofOTemp.getApplicationId() );
		
	
		String applicationCompleteJSP = "";
		if (applicationType
				.equalsIgnoreCase(ApplicationCofOConstants.APPLICATION_TYPE_INDIVIDUAL)) {
			applicationCompleteJSP = "/html/bocofo/individual/CofOIndividual.jsp";
		} else {
			applicationCompleteJSP = "/html/bocofo/organisation/CofOOrganisation.jsp";
		}
		
		actionRequest.setAttribute("jspPage", applicationCompleteJSP);
		actionResponse.setRenderParameter("jspPage", applicationCompleteJSP);
	}

	public void serveResource (
	    		ResourceRequest resReq, ResourceResponse resRes)
    throws IOException, PortletException
    {
    	
    	HttpServletRequest convertReq = PortalUtil.getHttpServletRequest(resReq);
    	HttpServletRequest originalReq = PortalUtil.getOriginalServletRequest(convertReq);
    	      
     	//get the download type
    	String downloadType = resReq.getParameter("downloadType");
    	if("static".equalsIgnoreCase(downloadType)){
    		String staticFileLoc = this.getInitParameter("static-file-location");
        	
        	String fileNameToDownload = resReq.getParameter("fileName"); //originalReq.getParameter("_Download_fileName");
        	
        	System.out.println("fileNameToDownload new --->>>" + resReq.getParameter("fileName"));
        	
        	File newFile = new File( staticFileLoc + "//" + fileNameToDownload + ".pdf");
        	 
        	resRes.setContentType("application/pdf");
        	resRes.setContentLength((int) newFile.length());
        	
        	String newReplaced = fileNameToDownload.replaceAll(" ", "");
        	
        	resRes.setProperty("Content-Disposition", "attachment; filename=" + newReplaced +".pdf");
        	
        	FileInputStream fis = new FileInputStream (newFile) ;
        	
        	byte[] readStream = new byte [(int) newFile.length()];
    		fis.read(readStream );
        	
        	resRes.getPortletOutputStream().write(readStream);
        	
        	fis.close();
    	}else{
    		String documentId = resReq.getParameter("documentId"); 
    		
    		Supporting_Document supportDoc = DownloadUtil.getSupportingDocument(documentId);
    		
    		Documents document = DownloadUtil.getDocument(documentId);
    		
    		byte[] readStream = Base64.decode(document.getDocumentUpload());
    		
    		resRes.setProperty("Content-Disposition", "attachment; filename=" + supportDoc.getFileName().replaceAll(" ", "_") );
        	
    		resRes.getPortletOutputStream().write(readStream);
    	}
    	
    }


	/**
	 * This method is used to override the addSuccessMessage in the parent
	 * class. This override ensures that success message (that is displayed as
	 * default whenever any request is successfully submitted) is prevented.
	 * 
	 * We like to have control over this and this what this override ensures.
	 * 
	 */
	@Override
	protected void addSuccessMessage(ActionRequest actionRequest,
			ActionResponse actionResponse) {

		if (!addProcessActionSuccessMessage) {
			return;
		}
	}
}
